<?php

/**
 * section actions.
 *
 * @package    berta-s
 * @subpackage section
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class sectionActions extends sfActions {
	private function initSection(){
		$section = $this->getRoute()->getObject();
		$this->forward404Unless($section, "Object doesnt exist");
		return $section;
	}

	/* @TODO: DRY up. duplicate with entry/image! */
	/* @TODO: remove incoming data container ("section") */
	private function saveSectionFromRequest(sfWebRequest $request){
		if ($request->hasParameter("section")) {
			$form=new SectionFormForBackend($this->section);
			$inputParams=$request->getParameter("section");
			// have no idea, why we need this, Entry should be initialized from form contructor
			if (!empty($this->section)){
				$inputParams["id"]=$this->section->getId();
			}

			$useFields=array();
			foreach ($inputParams as $name => $param){
				$useFields[]=$name;
			}
			if (sizeof($useFields)>0){
				$form->useFields($useFields);
			}

			$form->bind($inputParams);
			if ($form->isValid()) {
				$form->save();
				$values=array();
				$values["id"]=$form->getObject()->getId();
				foreach ($inputParams as $key => $value){
					if ($key!="id" && $key!="_csrf_token"){
						$values[$key]=$form->getValue($key);
					}
				}
				$this->values=$values;

				$this->setTemplate("XMLHttp", "global");
			}else{
				$this->setTemplate("XMLHttpError", "global");
			}
			$this->form=$form;
		}else{
			$this->setTemplate("XMLHttp");
		}
	}

//	public function preExecute(){
//		$request=$this->getRequest();
//		if ($request->isXmlHttpRequest()){
//			$request->setParameter("sf_format", "json");
//		}
//	}

	public function executeCreate(sfWebRequest $request){
		$this->saveSectionFromRequest($request);
	}

	public function executeUpdate(sfWebRequest $request){
		$this->section=$this->initSection();
		$this->saveSectionFromRequest($request);
	}

	public function executePromote(sfWebRequest $request){
		$this->section=$this->initSection();
		$this->section->promote();
		$this->setTemplate("XMLHttp", "global");
	}

	public function executeDemote(sfWebRequest $request){
		$this->section=$this->initSection();
		$this->section->demote();
		$this->setTemplate("XMLHttp", "global");
	}

	public function executeDelete(sfWebRequest $request){
		$this->section=$this->initSection();
		$this->section->delete();
		$this->setTemplate("XMLHttp", "global");
	}


}
